package com.lagou;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.lagou.bean.ConsumerComponent;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.io.IOException;
import java.sql.SQLOutput;
import java.util.concurrent.*;

import static java.lang.Thread.sleep;


public class AnnotationConsumerMain {

    private static int coreSize = Runtime.getRuntime().availableProcessors();

    private static final ThreadFactory THREAD_FACTORY =
            new ThreadFactoryBuilder().setNameFormat("dubbo-client-pool-%d").build();

    private static ExecutorService pool = new ThreadPoolExecutor(
            coreSize, coreSize * 2
            , 0L, TimeUnit.SECONDS, new LinkedBlockingDeque<>(5000),
            THREAD_FACTORY, new ThreadPoolExecutor.DiscardOldestPolicy()
    );

    public static void main(String[] args) throws IOException, InterruptedException {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConsumerConfiguration.class);
        context.start();
        ConsumerComponent service = context.getBean(ConsumerComponent.class);
        while (true) {
            System.in.read();
            long startTime = System.currentTimeMillis();
            try {
                for (int i = 0; i < 200; i++) {
                    for (int jj = 0; jj < 6; jj++) {
                        pool.submit(() -> {
                            service.callMethodA();
                        });
                    }
                    for (int jj = 0; jj < 3; jj++) {
                        pool.submit(() -> {
                            service.callMethodB();
                        });
                    }
                    for (int jj = 0; jj < 2; jj++) {
                        pool.submit(() -> {
                            service.callMethodC();
                        });
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            long endTime = System.currentTimeMillis();
            System.out.println("------总共花费时间" + (endTime - startTime) + "-----") ;
        }
    }

    @Configuration
    @PropertySource("classpath:/dubbo-consumer.properties")
    //@EnableDubbo(scanBasePackages = "com.lagou.bean")
    @ComponentScan("com.lagou.bean")
    @EnableDubbo
    static class ConsumerConfiguration {

    }
}
